<?php
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;


use app\admin\model\Abnormal;
use app\admin\model\Unit;
use app\admin\model\User;

/**
 * 异常分类管理-服务类
 *
 * @author  牧羊人
 * @since   : 2023/08/31
 * Class AbnormalService
 * @package app\admin\service
 */
class AbnormalService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new Abnormal();
    }

    /**
     * 获取数据列表
     *
     * @author 牧羊人
     * @return array
     * @since  2023/08/31
     */
    public function getList()
    {
        $param = request()->param();

        // 查询条件
        $map = [];


        // 所属模块
        $model_type = isset($param['model_type']) ? $param['model_type'] : '';
        if ($model_type) {
            $map[] = ['model_type', '=', $model_type];
        }

        // 异常分类名称
        $name = isset($param['name']) ? trim($param['name']) : '';
        if ($name) {
            $map[] = ['name', 'like', "%{$name}%"];
        }
        $level = isset($param['level']) ? trim($param['level']) : '';
        if ($level) {
            $map[] = ['level', '=', $level];
        }
        $unit_id = isset($param['unit_id']) ? (int)$param['unit_id'] : 0;
        if ($unit_id) {
            $map[] = ['unit_id', '=', $unit_id];
        }
        // 状态
        $status = isset($param['status']) ? (int)$param['status'] : 0;
        if ($status) {
            $map[] = ['status', '=', $status];
        }
        $sort   = 'id desc';
        $is_sql = 0;

        // 获取参数
        $argList = func_get_args();
        if (!empty($argList)) {
            // 查询条件
            $map = (isset($argList[0]) && !empty($argList[0])) ? $argList[0] : [];
            // 排序
            $sort = (isset($argList[1]) && !empty($argList[1])) ? $argList[1] : 'id desc';
            // 是否打印SQL
            $is_sql = isset($argList[2]) ? isset($argList[2]) : 0;
        }

        // 设置查询条件
        if (is_array($map)) {
            $map[] = ['mark', '=', 1];
        } elseif ($map) {
            $map .= " AND mark=1 ";
        } else {
            $map .= " mark=1 ";
        }

        // 打印SQL
        if ($is_sql) {
            echo $this->model->getLastSql();
        }
        $result = $this->model->where($map)->order($sort)->page(PAGE, PERPAGE)->column("id");
        $list   = [];
        if (is_array($result)) {
            foreach ($result as $val) {
                $info   = $this->model->getInfo($val);
                $list[] = $info;
            }
        }
        //获取数据总数
        $count     = $this->model->where($map)->count();
        $unitModel = new Unit();
        foreach ($list as $key => &$value) {
            $unit               = $unitModel->where(['id' => $value['unit_id']])->find();
            $value['unit_name'] = $unit['unit_name'];
            $value['unit_num']  = $unit['unit_num'];
            $pval               = $this->model->getInfo($value['pid']);
            $value['pname']     = $pval['name'];
        }
        //返回结果
        $message = array(
            "msg"   => '操作成功',
            "code"  => 0,
            "data"  => $list,
            "count" => $count,
        );

        return $message;

        return parent::getList($map); // TODO: Change the autogenerated stub
    }

    public function tree($param, $userId)
    {
        $query = clone $this->model->where('status', 2)->where('mark', 1);
        if (!empty($param['model_type'])) {
            $query->where('model_type', $param['model_type']);
        }
        if (!empty($param['unit'])) {
            $query->where('unit_id', $param['unit']);
        }
        if (!empty($param['name'])) {
            $query->where('name', 'like', "%{$param['name']}%");
        }
        if (!empty($param['level'])) {
            $query->where('level', $param['level']);
        }
        if (isset($param['status'])) {
            $query->where('status', $param['status']);
        }
        if (empty($param['all'])) {
            $query->field('id, pid, name');
        }
        if ($userId) {
            $user = User::find($userId);
        }
        if (empty($param['all']) && !empty($user->auth) && $user->auth != 'all') {
            $auth = explode(',', $user->auth);
            $all = (new Abnormal)->whereIn('id', $auth)->column('parent_tree');
            $authIds = $auth;
            foreach ($all as $val) {
                $authIds = array_merge($authIds, explode(',', $val));
            }
            $query->whereIn('id', array_unique($authIds));
        }
        $data = $query->select()->toArray();
        if (!empty($param['all'])) {
            $unitIds = array_column($data, 'unit_id');
            $units   = (new Unit())->whereIn('id', $unitIds)->column('unit_name', 'id');
        }

        $module = [
            'emergency'  => ['id' => -4, 'name' => '应急', 'children' => []],
            'protection' => ['id' => -3, 'name' => '环保', 'children' => []],
            'way'        => ['id' => -2, 'name' => '道路交通', 'children' => []],
            'illegal'    => ['id' => -1, 'name' => '违建', 'children' => []]
        ];

        $tree   = [];
        $refMap = [];
        foreach ($data as &$node) {
            if (!empty($param['all'])) {
                $node['module']      = $module[$node['model_type']]['name'];
                $node['unit_name']   = $units[$node['unit_id']] ?? '';
                $node['update_time'] = $node['update_time'] ?: $node['create_time'];
            }
            $refMap[$node['id']] = &$node;
            if ($node['pid'] === 0) {
                $tree[] = &$node;
            } else {
                $parent               = &$refMap[$node['pid']];
                $parent['children'][] = &$node;
            }
        }
        unset($node);
        if (!empty($param['all']) && empty($param['model_type'])) {
            foreach ($tree as $val) {
                $module[$val['model_type']]['model_type'] = $val['model_type'];
                $module[$val['model_type']]['children'][] = $val;
            }
            $tree = array_values($module);
        }

        return $tree;
    }

    public function getTreeById($id, $tree = null)
    {
        $func = function ($tree, $id) use (&$func) {
            foreach ($tree as $item) {
                if ($item['id'] == $id) {
                    return [$item['name']];
                }
                if (!empty($item['children'])) {
                    $parentNames = $func($item['children'], $id);
                    if ($parentNames !== null) {
                        array_unshift($parentNames, $item['name']);

                        return $parentNames;
                    }
                }
            }

            return null;
        };
        if (is_null($tree)) {
            $tree = $this->tree([], 0);
        }

        return $func($tree, $id);
    }
}